/**
 * modalEffects.js v1.0.0
 * http://www.codrops.com
 *
 * Licensed under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright 2013, Codrops
 * http://www.codrops.com
 */
var ModalEffects = (function() {

	function init() {

		$("body").append('<div class="md-overlay"></div>');

		var overlay = $('.md-overlay');

		$('.md-trigger').each(function(){
			var that = $(this);

			var modal = $('#'+that.data('modal')),
				close = modal.find('.md-close');

			function removeModal(hasPerspective){
				modal.removeClass('md-show');
				overlay.removeClass('md-overlay-show');

				if(hasPerspective){
					$(document.documentElement).removeClass('md-perspective');
				}
			}

			function removeModalHandler(){
				removeModal(that.hasClass('md-setperspective'));
			}

			that.on('click', function(ev){
				modal.addClass('md-show');
				overlay.addClass('md-overlay-show');
				//overlay.removeEventListener( 'click', removeModalHandler );
				//overlay.addEventListener( 'click', removeModalHandler );

				if(that.hasClass('md-setperspective')){
					setTimeout( function() {
						$(document.documentElement).addClass('md-perspective');
					}, 25 );
				}
			});

			close.on('click', function(e){
				e.stopPropagation();
				removeModalHandler();
			});

			overlay.on('click', function(e){
				//console.log('overlay');
				e.stopPropagation();
				removeModalHandler();
			});
		});

	}

	init();

})();

//手动打开模态框
$.fn.openModal = function(position_type){
	var openModal = function(element) {
		//model展示
		element.addClass('md-show');
		//over层展示
		var overlay = $('.md-overlay');
		overlay.addClass('md-overlay-show');
		//关闭按钮点击事件
		element.find('.md-close').on('click', function(){
			//model隐藏
			element.removeClass('md-show');
			//over层隐藏
			var overlay = $('.md-overlay');
			overlay.removeClass('md-overlay-show');
		});
	};
	return $(this).each(function() {
		openModal($(this));
	});
};

//手动关闭模态框
$.fn.closeModal = function(position_type){
	var closeModal = function(element) {
		element.removeClass('md-show');
		var overlay = $('.md-overlay');
		overlay.removeClass('md-overlay-show');
	};
	return $(this).each(function() {
		closeModal($(this));
	});
};